package com.moxigua.iotbox.func.image;


import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.moxigua.iotbox.R;
import com.moxigua.iotbox.base.BaseApplication;
import com.moxigua.iotbox.base.BaseFragment;
import com.moxigua.iotbox.base.Constants;
import com.moxigua.iotbox.bean.BaseRequest;
import com.moxigua.iotbox.bean.MqttAction;
import com.moxigua.iotbox.bean.ResponseCollection;
import com.moxigua.iotbox.bean.ResponseDeviceStatusAction;
import com.moxigua.iotbox.bean.ResponseImage;
import com.moxigua.iotbox.func.MqttClientHepler;
import com.moxigua.iotbox.func.event.BaseEvent;
import com.moxigua.iotbox.util.SPUtils;
import com.moxigua.iotbox.util.TimeUtil;
import com.orhanobut.logger.Logger;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.moxigua.iotbox.util.TimeUtil.FORMAT_DATE_TIME;

/**
 * A simple {@link Fragment} subclass.
 */
public class ImageFragment extends BaseFragment {


    @BindView(R.id.iv_image)
    ImageView mIvImage;
    @BindView(R.id.btn_request_image)
    Button mBtnRequestImage;
    @BindView(R.id.tv_time)
    TextView mTvTime;
    private Gson mGson;
    private Type mType;

    public ImageFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (!EventBus.getDefault().isRegistered(this))
        {
            EventBus.getDefault().register(this);
        }
        mGson = new Gson();
        View view = inflater.inflate(R.layout.fragment_image, container, false);
        ButterKnife.bind(this, view);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
////                requestImage();
//            }
//        }, 2000);
        mType = new TypeToken< MqttAction<ResponseImage, String>>() {}.getType();
        Logger.d(SPUtils.get(Constants.SP_CLIENT_ID, 999));
        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseEvent(BaseEvent event) {
        //判断主题
        if (event.topic.equals(Constants.TOPIC_SUB_REMOTE)) {
            String json = event.message.toString();
            if (json.contains("\"Image\"")) {
                mTvTime.setText(TimeUtil.longToString(new Date().getTime(), FORMAT_DATE_TIME));
                String jsonStr = json.substring(1, json.length() - 1);  //去除最外侧的[]
                MqttAction<ResponseImage, String> responseImageStringMqttAction =  mGson.fromJson(jsonStr, mType);
                if (responseImageStringMqttAction.getTags().getClientID() == (Integer) SPUtils.get(Constants.SP_CLIENT_ID, 0)) {
                    if (TextUtils.isEmpty(responseImageStringMqttAction.getValue())) {
                        showShortToast("未获取图片");
                    } else {
                        Picasso.with(getActivity()).load(responseImageStringMqttAction.getValue()).into(mIvImage);
                    }
                }
            }
        }
    }


    @OnClick(R.id.btn_request_image)
    public void onClick() {
        requestImage();
    }

    private void requestImage() {
        MqttAction<BaseRequest, Double> requestOnlineAction = new MqttAction<>();
        requestOnlineAction.setMetric(Constants.METRIC_REQUEST_IMAGE);
        BaseRequest requestOnline = new BaseRequest();
        int randomPacketId = (int) (Math.random() * 10000);
        BaseApplication.setLastPacketId(randomPacketId);
        requestOnline.setPacketID(randomPacketId);
        requestOnline.setClientid((Integer) SPUtils.get(Constants.SP_CLIENT_ID, 0));
        requestOnlineAction.setTags(requestOnline);
        requestOnlineAction.setValue(Double.valueOf(0));
        String payload = "[" + new Gson().toJson(requestOnlineAction) + "]";
        Logger.d(payload);
        MqttClientHepler.getInstance().publish(Constants.TOPIC_PUB_DEV, 1, payload.getBytes());
    }
}
